package product

import (
	"context"
	"gitee.com/zyw0605688_admin/gozero/product_service/model"

	"gitee.com/zyw0605688_admin/gozero/product_service/internal/svc"
	"gitee.com/zyw0605688_admin/gozero/product_service/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductListLogic {
	return &ProductListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ProductListLogic) ProductList(req *types.ProductListRequest) (resp *types.ProductListResponse, err error) {
	list := []model.Product{}
	total := int64(0)
	sqlQuery := l.svcCtx.DB.Model(&model.Product{})
	totalQuery := l.svcCtx.DB.Model(&model.Product{})
	if req.PageSize > 0 && req.PageNum > 0 {
		sqlQuery.Offset((req.PageNum - 1) * req.PageSize).Limit(req.PageSize)
	}
	if req.ProductName != nil {
		sqlQuery.Where("product_name like ?", "%"+*req.ProductName+"%")
		totalQuery.Where("product_name like ?", "%"+*req.ProductName+"%")
	}
	err = sqlQuery.Find(&list).Error
	err = totalQuery.Count(&total).Error
	if err != nil {
		return nil, err
	}
	resList := []types.ProductDetailResponse{}
	for _, v := range list {
		productTypeName := ""
		err = l.svcCtx.DB.Raw("select product_type_name from product_type where id = ?", v.ProductTypeId).Scan(&productTypeName).Error
		if err != nil {
			return nil, err
		}
		resList = append(resList, types.ProductDetailResponse{
			Id:              v.Id,
			ProductName:     v.ProductName,
			ProductPrice:    v.ProductPrice,
			ProductDesc:     v.ProductDesc,
			ProductTypeId:   v.ProductTypeId,
			ProductTypeName: productTypeName,
			CreatedAt:       v.CreatedAt,
		})
	}
	resp = &types.ProductListResponse{
		List:  resList,
		Total: total,
	}

	return
}
